package com.rms.utils.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rms.domain.Admin;
import com.rms.domain.Company;
import com.rms.domain.CompanyManager;
import com.rms.domain.Hr;
import com.rms.domain.LoginForm;
import com.rms.domain.Worker;
import com.rms.service.AdminService;
import com.rms.service.CompanyManagerService;
import com.rms.service.CompanyService;
import com.rms.service.HRService;
import com.rms.service.WorkerService;
import com.rms.service.impl.AdminServiceImpl;
import com.rms.service.impl.CompanyManagerServiceImpl;
import com.rms.service.impl.CompanyServiceImpl;
import com.rms.service.impl.HRServiceImpl;
import com.rms.service.impl.WorkerServiceImpl;
import com.rms.utils.service.BaseService;

/**
 * 继承该类的servlet可以接收多个请求 该类内置多个Service
 * 
 * @author Zheng weiyu
 * @date 2019年7月29日
 */
@WebServlet("/BaseServlet")
public class BaseServlet extends HttpServlet {

	/** 所有可能用到的service */
	protected WorkerService workerService = new WorkerServiceImpl();
	protected CompanyService companyService = new CompanyServiceImpl();
	protected CompanyManagerService companyManagerService = new CompanyManagerServiceImpl();
	protected HRService hrService = new HRServiceImpl();
	protected AdminService adminService = new AdminServiceImpl();
	protected BaseService baseService = new BaseService();

	public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 得到角色id
		int role_id = Integer.valueOf(request.getParameter("role_id"));
		// 设置登录类、session_name、转发路径
		Class<?> clazz = null;
		String session_name = null;
		String path = null;
		String failPath = "login.jsp";
		if (role_id == 4) {
			clazz = Admin.class;
			session_name = "admin";
			path = "/ToAdminMainPageServlet";
		} else if (role_id == 3) {
			clazz = CompanyManager.class;
			session_name = "companyManager";
			path = "/ToManagerMainPageServlet";
		} else if (role_id == 2) {
			clazz = Hr.class;
			session_name = "hr";
			path = "/ToHRMainPageServlet";
		} else if (role_id == 1) {
			clazz = Worker.class;
			session_name = "worker";
			path = "/ToWorkMainPageServlet";
		}
		LoginForm loginForm = new LoginForm();
		try {
			if (request.getParameter("id").length() == 0) {
				throw new RuntimeException("用户名不能为空!");
			}
			// 封装用户名
			loginForm.setId(Integer.parseInt(request.getParameter("id")));
		} catch (RuntimeException e) {
			request.setAttribute("message", e.getMessage());
			request.getRequestDispatcher(failPath).forward(request, response);
		} catch (Exception e) {
			request.setAttribute("message", "请输入正确的用户名(8位数字)");
			request.getRequestDispatcher(failPath).forward(request, response);
		}
		// 封装密码
		loginForm.setPassword(request.getParameter("password"));

		try {

			Object obj = baseService.login(loginForm, clazz);
			request.getSession().setAttribute(session_name, obj);
			request.setAttribute("message", "登录成功!");
			request.getRequestDispatcher(path).forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("message", "登录失败!" + e.getMessage());
			request.getRequestDispatcher(failPath).forward(request, response);
		}
	}

	// 注册
	public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int role_id = Integer.parseInt(request.getParameter("role"));
		Object registRole;
		String password = request.getParameter("password");
		String password1 = request.getParameter("password1");
		/**
		 * 查询公司是否已存在,若已存在打回注册请求
		 */
		try {
			if (!password.equals(password1)) {
				throw new RuntimeException("密码不一致");
			}
			if (companyService.isExistCompany(request.getParameter("companyName"))) {
				throw new RuntimeException("公司已注册，不允许再次注册");
			}
		} catch (Exception e) {
			request.setAttribute("message", e.getMessage());
			request.getRequestDispatcher("regist.jsp").forward(request, response);
			//转发后结束该方法
			return;
		}
		// 根据角色的不同进行封装,注册
		if (role_id == 1) {
			// worker
			registRole = new Worker();
			String name = request.getParameter("username");
			String phone = request.getParameter("phone");
			String email = request.getParameter("email");
			((Worker) registRole).setName(name);
			((Worker) registRole).setPassword(password);
			((Worker) registRole).setPhone(phone);
			((Worker) registRole).setEmail(email);
			((Worker) registRole).setRoleId(role_id);
			// 进行注册
			try {
				workerService.regist((Worker) registRole);
				request.setAttribute("message", "注册成功!");
			} catch (Exception e) {
				e.printStackTrace();
				request.setAttribute("message", "注册失败");
			}
		} else if (role_id == 3) {
			// companyManager
			registRole = new CompanyManager();
			String companyName = request.getParameter("companyName");
			String address = request.getParameter("address");
			String companyPhone = request.getParameter("companyPhone");
			String companyEmail = request.getParameter("companyEmail");
			String description = request.getParameter("description");
			// 封装company
			Company company = new Company();
			company.setName(companyName);
			company.setAddress(address);
			company.setPhone(companyPhone);
			company.setEmail(companyEmail);
			company.setDescription(description);
			((CompanyManager) registRole).setCompany(company);

			// 封装manager
			((CompanyManager) registRole).setPassword(password);
			((CompanyManager) registRole).setRoleId(role_id);

			try {
				//注册公司，并返回该公司id
				Company c = companyService.registCompany(company);
				//将公司id封装到Manager对象上
				((CompanyManager) registRole).setCompanyId(c.getId());
				//注册manager
				companyManagerService.regist((CompanyManager) registRole);
				request.setAttribute("message", "注册成功!");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				request.setAttribute("message", "注册失败!");
			}

		}
		request.getRequestDispatcher("regist.jsp").forward(request, response);
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 传入method名称
		String methodName = (String) request.getParameter("method");
		if (methodName == null || methodName.trim().isEmpty()) {
			throw new RuntimeException("请传入方法名称(method=methodName)!");
		}
		Method method = null;
		try {
			// 判断method是否存在
			method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			// 若存在，反射调用
			method.invoke(this, request, response);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
			throw new RuntimeException("您调用的方法" + methodName + "不存在!");
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

}
